package Business;

import Message.Tips;
import Request.Send;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 音乐类
 */
public class Music {

    /**
     * 获取音乐批量音乐信息
     * @param idList 网易云音乐id，大量
     * @return url
     */
    private static JSONArray getMusicInfoList(List<String> idList){
        JSONObject data;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            for (String id : idList){
                stringBuilder.append(",").append(id);
            }
            stringBuilder.delete(0,1);
            Send html = new Send("http://cloud-music.pl-fe.cn/song/detail?ids=" + stringBuilder);
            html.doGet();
            data = html.getJson();
            html.disconnect();
        }catch (Exception e){
            return null;
        }
        JSONArray re;
        try {
            re = data.getJSONArray("songs");
        }catch (Exception e){
            return null;
        }
        return re;
    }

    /**
     * 获取音乐url
     * @param id 网易云音乐id
     * @return url
     */
    private static String getMusicUrl(String id){
        String re;
        JSONObject data;
        try {
            Send html = new Send("http://cloud-music.pl-fe.cn/song/url?id=" + id);
            html.doGet();
            data = html.getJson();
            html.disconnect();
        }catch (Exception e){
            return null;
        }
        try {
            re = data.getJSONArray("data").getJSONObject(0).getString("url");
        }catch (Exception e){
            return null;
        }
        return re;
    }

    /**
     * 获取单歌详细
     * @param id 网易云音乐id
     * @return 内容
     */
    public static Map<String ,Object> getMusicInfo(String id){
        Map<String , Object> reDate = new HashMap<>();
        JSONObject data;
        try {
            Send html = new Send("http://cloud-music.pl-fe.cn/song/detail?ids=" + id);
            html.doGet();
            data = html.getJson();
            html.disconnect();
        }catch (Exception e){
            return null;
        }
        try {
            JSONObject data2 = data.getJSONArray("songs").getJSONObject(0);
            reDate.put("id", data2.getString("id"));
            reDate.put("name", data2.getString("name"));
            StringBuilder art = new StringBuilder();
            JSONArray artists = data2.getJSONArray("ar");
            for (int i = 0; i < artists.size(); i++) {
                art.append(",").append(artists.getJSONObject(i).getString("name"));
            }
            art.delete(0, 1);
            reDate.put("artists", art.toString());
            reDate.put("duration", data2.getInt("dt"));
            reDate.put("imageUrl", data2.getJSONObject("al").getString("picUrl"));
            int fee = data2.getInt("fee");
            boolean isVip = fee != 0 && fee != 8;
            reDate.put("vip" , isVip);
            String url = getMusicUrl(id);
            if (url == null) return null;
            reDate.put("url", url);
        }catch (Exception e){
            return null;
        }
        return reDate;
    }

    /**
     * 搜索
     * @param content 搜素内容
     * @param page 页数
     */
    public static List<Object> search(String content , String page){
        String contentE;
        List<Object> reList = new ArrayList<>();
        try {
            contentE = URLEncoder.encode(content, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            Tips.Warm("音乐搜索编码转换异常！");
            return null;
        }
        JSONObject data;
        try {
            Send html = new Send("http://cloud-music.pl-fe.cn/search?keywords=" + contentE + "&offset=" + page);
            html.doGet();
            data = html.getJson();
            html.disconnect();//关闭
        } catch (Exception e) {
            Tips.Warm("api网页访问异常！");
            return null;
        }
        if (data == null || data.get("code") == null) return reList;
        String code = data.get("code").toString();
        if(!code.equalsIgnoreCase("200")) return reList;
        try {
            JSONArray songs = ((JSONObject) data.get("result")).getJSONArray("songs");
            List<String> songList = new ArrayList<>();
            for (Object songObj : songs){//获取所有歌曲详细情况
                JSONObject song = JSONObject.fromObject(songObj);
                songList.add(song.get("id").toString());
            }
            JSONArray songDetailed = getMusicInfoList(songList);
            if (songDetailed == null) return null;
            int i = 0;//索引
            for (Object songObj : songs) {
                JSONObject song = JSONObject.fromObject(songObj);
                Map<String, Object> music = new HashMap<>(8);
                JSONObject songDeta = songDetailed.getJSONObject(i);
                music.put("id", song.get("id"));
                music.put("name", song.get("name"));
                JSONArray artists = song.getJSONArray("artists");
                StringBuilder art = new StringBuilder();
                for (Object artistObj : artists) {
                    JSONObject artist = JSONObject.fromObject(artistObj);
                    art.append(",");
                    art.append(artist.getString("name"));
                }
                art.delete(0, 1);
                music.put("artists", art.toString());
                music.put("duration", song.get("duration"));
                music.put("imageUrl", songDeta.getJSONObject("al").getString("picUrl"));
                int fee = songDeta.getInt("fee");
                boolean isVip = fee != 0 && fee != 8;
                music.put("vip" , isVip);
                reList.add(music);
                i ++;
            }
        }catch (Exception e){
            Tips.Warm("JSON异常！");
            return null;
        }
        return reList;
    }








}
